package stack

import (
	"container/list"
	"strings"
)

// https://leetcode.cn/problems/simplify-path leetcode-71
func simplifyPath(path string) string {
	pathStr := "/"
	split := strings.Split(path, pathStr)
	l := list.New()
	for _, s := range split {
		if len(s) > 0 && s != "." && s != ".." {
			l.PushFront(s)
		} else if s == ".." {
			e := l.Front()
			if e != nil {
				l.Remove(e)
			}
		}
	}

	sb := strings.Builder{}
	sb.WriteString(pathStr)
	for node := l.Back(); node != nil; node = node.Prev() {
		sb.WriteString(node.Value.(string))
		sb.WriteString(pathStr)
	}
	result := sb.String()
	if len(result) > 1 {
		return result[:len(result)-1]
	}
	return result
}
